let tempDataList = [];
let pageNum = 1;
let pageSize = 10;
let scrollContainer = document.getElementById('scrollContainer');
let lastLoadStatus = true;
let lastKeyWord = '';

$(function () {
    loadDeviceUserData();

    // 无限滚动
    $('.mainContent').on('scroll', function () {
        const scrollTop = scrollContainer.scrollTop;
        const scrollHeight = scrollContainer.scrollHeight;
        const clientHeight = scrollContainer.clientHeight;

        if (lastLoadStatus && (scrollTop + clientHeight >= scrollHeight - 50)) {
            lastLoadStatus = false;
            pageNum++;
            loadDeviceUserData();
        }
    });
})

function loadDeviceUserData() {
    showLoading();

    const keyWord = $("#selectItem").val();

    if (keyWord.trim().length > 0 && keyWord !== lastKeyWord) pageNum = 1;

    lastKeyWord = keyWord;

    $.post(serverUrl + ':' + serverPort + serverName + '/deviceUser/findDeviceUserTempList', {
        userId: sessionStorage.getItem("selectUserId"), keyWord: keyWord, companyId: sessionStorage.getItem("selectCompanyId"), pageNum: pageNum, pageSize: pageSize
    }, function (result) {
        hideLoading();

        let obj = JSON.parse(result);

        tempDataList = tempDataList.concat(obj.data.content);
        renderData(tempDataList);

        lastLoadStatus = true;

        // 开关状态保存
        document.querySelectorAll('input[type="checkbox"]').forEach(switchEl => {
            switchEl.addEventListener('change', function () {
                const state = this.checked;
                const info = $(this).next().data('type');
                const deviceCode = info.split('-')[0];
                const type = info.split('-')[1];

                updateDeviceUser(deviceCode, type, state ? 1 : 0);
            });
        });
    });
}

// 渲染底部显示数据
function renderData(dataList) {
    let content = '';

    $.each(dataList, function (i, item) {
        content += '<div class="card">';
        content += '<div class="card-content">';

        if (null !== item.device.company) {
            content += '<div class="card-title">' + item.device.company.name + ' - ' + item.device.name + '</div>';
        } else {
            content += '<div class="card-title">' + item.device.name + '</div>';
        }

        content += '<div class="switch-group">';

        // 实时数据选项开关
        content += '<div class="switch-item">';
        content += '<label class="switch">';
        if (item.timeFlag === 1) {
            content += '<input type="checkbox" checked>';
        } else {
            content += '<input type="checkbox">';
        }
        content += '<span class="slider" data-type="' + item.device.code + '-2011"></span>';
        content += '</label>';
        content += '<span class="switch-label">实时预警</span>';
        content += '</div>';

        // 分钟数据选项开关
        content += '<div class="switch-item">';
        content += '<label class="switch">';
        if (item.minuteFlag === 1) {
            content += '<input type="checkbox" checked>';
        } else {
            content += '<input type="checkbox">';
        }
        content += '<span class="slider" data-type="' + item.device.code + '-2051"></span>';
        content += '</label>';
        content += '<span class="switch-label">分钟预警</span>';
        content += '</div>';

        // 小时数据选项开关
        content += '<div class="switch-item">';
        content += '<label class="switch">';
        if (item.hourFlag === 1) {
            content += '<input type="checkbox" checked>';
        } else {
            content += '<input type="checkbox">';
        }
        content += '<span class="slider" data-type="' + item.device.code + '-2061"></span>';
        content += '</label>';
        content += '<span class="switch-label">小时预警</span>';
        content += '</div>';

        // 日均数据选项开关
        content += '<div class="switch-item">';
        content += '<label class="switch">';
        if (item.dayFlag === 1) {
            content += '<input type="checkbox" checked>';
        } else {
            content += '<input type="checkbox">';
        }
        content += '<span class="slider" data-type="' + item.device.code + '-2031"></span>';
        content += '</label>';
        content += '<span class="switch-label">日均预警</span>';
        content += '</div>';

        // 查看数据选项开关
        content += '<div class="switch-item">';
        content += '<label class="switch">';
        if (item.dataFlag === 1) {
            content += '<input type="checkbox" checked>';
        } else {
            content += '<input type="checkbox">';
        }
        content += '<span class="slider" data-type="' + item.device.code + '-1010"></span>';
        content += '</label>';
        content += '<span class="switch-label">查看数据</span>';
        content += '</div>';

        content += '</div>';
        content += '</div>';
        content += '</div>';
    });

    $('.mainContent').html(content);
}

// 修改用户设备关联关系
function updateDeviceUser(deviceCode, type, flag) {
    showLoading();

    $.post(serverUrl + ':' + serverPort + serverName + '/deviceUser/updateDeviceUser', {
        deviceCode: deviceCode, userId: sessionStorage.getItem("selectUserId"), type: type, flag: flag
    }, function (result) {
        hideLoading();

        let obj = JSON.parse(result);

        if (obj.code === 0) {
            // 显示成功消息（3秒后自动关闭）
            if (flag === 0) {
                showMessage('success', '状态修改成功！');
            } else {
                showMsg('状态修改成功');
            }
        } else {
            // 显示错误消息（带标题）
            showMessage('error', '无法连接到服务器', '连接错误');
        }
    });
}

// 获取DOM元素
const userInput = document.getElementById('selectItem');

// 状态变量
let isComposing = false; // 用于检测中文输入状态
let lastValue = ''; // 上次保存的值

// 内容变化处理函数（防抖后）
function handleContentChange() {
    const currentValue = userInput.value;

    // 内容实际发生变化时才处理
    if (currentValue !== lastValue) {
        lastValue = currentValue;
        tempDataList = [];
        loadDeviceUserData();
    }
}

// 创建防抖函数
function debounce(func, delay) {
    let timer;
    return function () {
        clearTimeout(timer);
        timer = setTimeout(() => {
            func.apply(this, arguments);
        }, delay);
    };
}

// 创建500ms防抖的内容变化处理器
const debouncedChangeHandler = debounce(handleContentChange, 500);

// 事件监听
userInput.addEventListener('input', function () {
    // 中文输入过程中不触发
    if (!isComposing) {
        debouncedChangeHandler();
    }
});

// 处理中文输入法事件
userInput.addEventListener('compositionstart', function () {
    isComposing = true;
});

userInput.addEventListener('compositionend', function () {
    isComposing = false;
    debouncedChangeHandler(); // 中文输入完成，触发变化检测
});